<template>
  <div class="gantt__layout" :style="{ maxWidth: `calc(100px + ${baseHour * 24}px)`}">
    <!--头部组件：可选配置-->
    <chart-header :header-data="headerData" ref="chearHeader" @scrollContainer="scrollContainer"/>
    <!--甘特图区域组件：必选-->
    <template v-if="ganttData.length">
      <div class="gantt__area" :style="areaStyleObj">
        <!--甘特图Side数据组件-->
        <chart-side :gantt-data="chartData" @agendaUserCard='agendaUserCard'/>
        <!--甘特图中心数据组件 -->
        <chart-container id="gantt-container" :gantt-data="chartData" />
      </div>
    </template>
    <!-- 无数据区域 避免闪动问题不用v-else-->
    <template v-if="ganttData.length<=0">
      <div class="gantt__area--error">
        <img :src="noDataImage">
        <span>{{$t('common.base.tip.noData')}}</span>
      </div>
    </template>
  </div>
</template>

<script>
import ChartHeader from './chart-header'
import ChartContainer from './chart-container'
import ChartSide from './chart-side'
import moment from 'moment'
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import i18n from '@src/locales'
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')

export default {
  name: 'gantt-chart',
  components: { ChartHeader, ChartSide, ChartContainer },
  provide() {
    return {
      // timeSectionDayJs: this.timeSectionDayJs,
      // baseHour: this.baseHour,
      // baseBlock: this.baseBlock,
      ganttChartInstance: this
    }
  },
  props: {
    headerData: {
      // 甘特图表头自定义
      type: Array,
      default: () => [i18n.t('common.base.date'), i18n.t('common.base.time')],
    },
    timeSection: {
      // 甘特图时间区间
      type: Array,
      required: true,
    },
    chartMaxHeight: {
      // 甘特图内容最大高度
      type: Number,
      default: 500,
    },
    ganttCurrentTime: {
      // 甘特图时间轴时间
      type: Number,
      default: safeNewDate().getTime(),
    },
    ganttData: {
      // 甘特图数据
      type: Array,
      required: true,
    },
    type: {
      // 判断工单事件
      type: String,
      default: '',
    },
    acceptEnable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      //
      baseHour: 50, // 基准小时
      baseBlock: 40, // 基准高度
      noDataImage
    }
  },
  computed: {
    areaStyleObj() {
      // 自适应高度限制
      const realHeight = this.ganttData.length * this.baseBlock
      return {
        height: `${
          realHeight > this.chartMaxHeight ? this.chartMaxHeight : realHeight
        }px`,
      }
    },
    timeSectionDayJs() {
      // 传入的甘特图时间区间转化为DayJs区间
      const [startTime, endTime] = this.timeSection.map((item) => moment(item))
      if (startTime.isValid() && endTime.isValid()) {
        return { startTime, endTime }
      }
      console.error(`传入的时间区间${this.timeSection}不是合法的`)
      return {}
    },
    chartData() {

      // 这是一坨屎
      const [ startTime, endTime ] = this.timeSection.map((item) => moment(item));
      return this.ganttData.map((item) => {
        if(item?.agendaDtos) { // agendaDtos可能为null
          item.agendaDtos = item.agendaDtos.map(agenda=>{
            
            const aE =  formatDate(safeNewDate(agenda.endTime),'yyyy-MM-dd HH:mm:ss');
            const dE =  formatDate(endTime.$d,'yyyy-MM-dd') + ' 23:59:59';
            if(safeNewDate(aE).getTime() > safeNewDate(dE).getTime()){
              agenda.endTime = dE;
            }
            return agenda;
          });
        };
        return item;
      })
      
    },
  },
  watch:{
    chartData:{
      handler(n,o){
        // 冲突切换错位问题
        setTimeout(()=>{
          const header = document.querySelector('.gantt__layout .header__container');
          const container = document.querySelector('.gantt__layout .container');
          if(container) container.scrollLeft = header.scrollLeft;
        },50);

        this.synchronousScoll()
      },
      deep: true
    }
  },
  methods: {
    // 日期切换同步
    scrollContainer(type) {
      this.$nextTick(() => {
        const container = document.querySelector('.gantt__layout .container');
        const header = document.querySelector('.gantt__layout .header__container')
        if(type === 'left') {
          if (header) {
            header.scrollLeft -= this.baseHour * 24
          }
          if (container) {
            container.scrollLeft -= this.baseHour * 24
          }
        }else if(type === 'right') {
          if (header) {
            header.scrollLeft += this.baseHour * 24;
          }
          if (container) {
            container.scrollLeft += this.baseHour * 24;
          }
        }else if(type === 'begin') {
          let startTime = this.timeSectionDayJs.startTime
          let diff = (this.baseHour * ((moment(startTime).hour() * 60) + moment(startTime).minute())) / 60
          if (header) {
            header.scrollLeft = diff;
          }
          if (container) {
            container.scrollLeft = diff;
          }
        }
      })
    },
    agendaUserCard(item) {
      this.$emit('agendaUserCard', item)
    },
    // 滚动同步
    synchronousScoll(){
      setTimeout(() => {
      this.$nextTick(() => {
        const header = document.querySelector(
          '.gantt__layout .header__container'
        )
        const side = document.querySelector('.gantt__layout .side')
        const container = document.querySelector('.gantt__layout .container')
        const area = document.querySelector('.gantt__layout')
        let flag = ''
        
        area.addEventListener(
          'mouseenter',
          (event) => {
            const className = event.target.className
            if (className.includes('container')) flag = 'container'
            if (className.includes('side')) flag = 'side'
          },
          true
        )

        area.addEventListener(
          'scroll',
          (event) => {
            if (
              flag === 'container' &&
              (event.target.className === 'container' ||
              event.target.className === 'header__container')
            ) {
              if (side) {
                side.scrollTop = event.target.scrollTop
              }
              if (header) {
                header.scrollLeft = event.target.scrollLeft
                let evertWidth = this.baseHour * 24;
                let index = Math.floor(header.scrollLeft/evertWidth)
                this.$refs.chearHeader.updateDay(index);
              }
              if (container) {
                container.scrollLeft = event.target.scrollLeft
              }
            }
            if (flag === 'side' && container)
              container.scrollTop = event.target.scrollTop
          },
          true
        )
      })
    })
    }
  },
  mounted() {
    // 滚动同步
    this.synchronousScoll()
  },
}
</script>

<style lang="scss" scoped>
// 甘特图全局布局
.gantt__layout {
  margin: 12px 0 0 0;
  padding: 0;
  overflow: hidden;
  // border: 1px solid #e0e1e2;
}
.gantt__area {
  display: grid;
  grid-template-columns: 100px 1fr;
}
.gantt__area--error {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  font-size: 1em;
  color: $text-color-regular;
  img {
    width: 160px;
    height: 160px;
    margin-bottom: 8px;
  }
}
</style>
